<?php

class Resource_Backend_Action_Common_Edit extends Kernel_Action_Form_Simple 
{
    
    /**
    * @desc Menu name. 
    * 
    * @param string
    */
    public $navigation;
    
    /**
     * Путь к файлу шаблона.
     *
     * @var string
     */
    protected $_template = 'resource/container.tpl';
    
    /**
     * Основная таблица, в которой хранится редактируемый элемент.
     *
     * @var string
     */
    protected $_table = 'system_resource'; 
    
    /**
    * Background image name.
    * 
    * @var string
    */
    protected $_bg_image;
    
    
    /**
     * Initialize form elements. 
     *
     */
    protected function _initElements() 
    {
        parent::_initElements();
        
        $available_modules = $this->_avaliableModules();
        
        // in case of not available module do not allow change url and module
        // set to "read only"
        if ('add' != Application::getRequest()->get('action') && 
            !in_array($this->_getInitialValue('module'), 
            array_keys($available_modules))) 
        {
            $this->_setElementParam('url', array('readonly' => true, 'caption' => __('URL') . sup()));
            $this->_setElementParam('module', array('readonly' => true, 'caption' => __('MODULE') . sup()));
        } else {
            $this->_setElementParam('url', array('validators' => array('Resource_Validator_Uri')));
            $this->_setElementParam('module', array(
                'type' => 'list', 
                'values' => $available_modules, 
                ));
        }
        $this->_setElementParam('option', array(
            'type' => 'list', 
            'values' => array(), 
            ));
        $this->_setAsRequired('url', 'module');
        // pass option id to raise after option list will be filled
        if ('add' != Application::getRequest()->get('action')) {
            $this->_addElement('option_id', 'hidden', array(
                'value' => $this->_getInitialValue('option'), 
            ));
            $this->_buttons($this->_avaliableModules());
        }
        
        
        
        
        
        $this->_setElementParam('url', array('type' => 'hidden'));
        $this->_setElementParam('name', array('type' => 'hidden'));
        $this->_setElementParam('module', array('type' => 'hidden'));
        $this->_setElementParam('option', array('type' => 'hidden'));
    }
    
    /**
    * Add buttons.
    * 
    */
    protected function _buttons($modules) 
    {
        if (in_array($this->_getInitialValue('module'), array_keys($modules))) 
        {
            Application::getResponse()->assign(array('buttons' => array(
                'delete' => Backend_Filter_Structure::get() + array(
                    'action' => 'delete', 'id' => $this->id), 
                )));
        }
    }
    
    /**
     * @desc Overlay load data to check current menu belonging.
     *
     * @return  array
     */
    protected function _load() 
    {
        static $data = array();
        
        if (empty($data)) {
            // mandatory specify menu name as resource with the same id may
            // belongs to different menus and certainly may has different positions
            $query = '
                SELECT 
                       `r`.*, 
                       `i`.`parent_id`, 
                       `i`.`position`
                  FROM 
                       `' . $this->_table . '` `r`, 
                       `system_navigation_item` `i`, 
                       `system_navigation` `n`
                 WHERE 
                       `i`.`resource_id` = `r`.`id` 
                   AND 
                       `n`.`id` = `i`.`menu_id` 
                   AND 
                       `r`.`id` = ' . (int)$this->id . ' 
                   AND 
                       `n`.`name` = "' . database::escape($this->navigation) . '"';
            $data = database::fetchRow($query);
        }
        
        return $data;
    }
    
    protected function _validate()
    {
        // prepare url
        $url = $this->_getValue('url');
        if (empty($url) && 
            !$this->_isEmptyUrlAllowed() && 
            $this->_elementExists('name')) 
        {
            $url = transliterate($this->_getValue('name'));
        }
        
        $this->_setValue('url', url($url));
        
        parent::_validate();
    }
    
    /**
    * Return whether empty url is allowed
    * 
    * @return boolean
    */
    private function _isEmptyUrlAllowed() 
    {
        $query = '
            SELECT EXISTS 
                      (SELECT 
                           `id` 
                      FROM 
                           `system_resource` 
                     WHERE 
                           `url` = ""
                       AND 
                           `id` != ' . (int)$this->id . ')
            ';
        return (bool)!database::fetchOne($query);
    }
    
    protected function _validateElement($name) 
    {
        // do not validate module options
        if ('option' == $name) {
            return;
        }
        
        if ('url' == $name) {
            // Allow url to be empty
            $this->_validateValue($name);
        } else {
            parent::_validateElement($name);
        }
    }
    
    /**
    * Simple form jumps here in case of DB-exception. Can be used for
    * callback actions, e.g. to build link for duplicate entry only if exception 
    * raised. 
    * 
    */
    protected function _exceptionCallback() 
    {
        $this->_map(MySQL::ER_DUP_ENTRY, __('URL_ER_DUP_ENTRY', $this->_duplicateLink()));
    }
    
    protected function _done() 
    {
        $redirect_link = 'add' == Application::getRequest()->get('action') 
            ? $this->_duplicateLink()
            : array();
        $this->_location($redirect_link);
    }
    
    /**
    * @desc Make link in case of duplicate entry.
    * 
    * @return string 
    */
    protected function _duplicateLink() 
    {
        $query = '
            SELECT 
                   `r`.`id`,
                   IFNULL(`n`.`name`, "hidden") `manager`
              FROM 
                   `system_resource` `r` 
         LEFT JOIN 
                   `system_navigation_item` `i` 
                ON 
                   `i`.`resource_id` = `r`.`id`
         LEFT JOIN 
                   `system_navigation` `n` 
                ON 
                   `i`.`menu_id` = `n`.`id`
             WHERE 
                   `r`.`url` = "' . database::escape($this->_getValue('url')) . '"
            ';
        
        if ($data = database::fetchRow($query)) {
            extract($data, EXTR_PREFIX_ALL, 'db');
            extract(Backend_Filter_Structure::get());
            return 
                sprintf('?lang=%s&section=%d&module=%s&manager=%s&action=edit&id=%d', 
                $lang, $section, $module, $db_manager, $db_id);
        }
        
        return array();
    }
    
    protected function _avaliableModules() 
    {
        return Resource_Backend_Utils::availableModules();
    }
    
}
